<template>
  <div>
    <div class="search_box">
      <el-form :inline="true" label-width="100px" :model="formData">
        <el-form-item>
          <el-input
            v-model="formData.keyword"
            placeholder="轮播图名称/Id"
            @clear="getList"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList">查 询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table_box_wrapper">
      <div style="margin: 0 0 0 12px">
        <el-button type="primary" @click="addApps">
          <el-icon style="margin-right: 5px">
            <Plus />
          </el-icon>
          新 增
        </el-button>
      </div>
      <custom-table
        :loading="loading"
        :columns="columns"
        :tableData="tableData"
        :isPagination="false"
        :maxheight="650"
        class="table_box"
      >
        <template #sort>
          <span
            class="move el-table"
            :style="{ cursor: dragvalue ? 'grabbing' : 'grab' }"
          >
            三
          </span>
        </template>
        <template #path="{ scope }">
          <div class="movie_box">
            <el-image
              v-if="scope.row?.path"
              class="img"
              :src="`https://theater-static-1320245876.cos.ap-guangzhou.myqcloud.com/${scope.row?.path}?${randN}`"
            />
            <!-- :preview-src-list="[
                `https://theater-static-1320245876.cos.ap-guangzhou.myqcloud.com/${scope.row?.path}?${randN}`,
              ]" -->
            <el-image class="img" v-else>
              <template #error>
                <div class="image-slot">
                  <el-icon><PictureFilled /></el-icon>
                </div>
              </template>
            </el-image>
          </div>
        </template>
        <template #enabled="{ scope }">
          <el-switch
            style="

--el-switch-on-color: #13ce66"
            :modelValue="scope.row.enabled"
            inline-prompt
            active-text="启用"
            inactive-text="禁用"
            @click.stop="handleStatus(scope.row)"
          />
        </template>
        <template #operator="{ scope }">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </custom-table>
    </div>

    <!-- 新增编辑信息 -->
    <info ref="infoRef" @success="getList" />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import type { Action } from "element-plus";
import { Plus, PictureFilled } from "@element-plus/icons-vue";
import Sortable from "sortablejs";
import customTable from "@/components/CustomTable/index.vue";
import info from "./components/bannerInfo.vue";
import {
  getBannerList,
  sortBanner,
  statusBanner,
  deleteBanner,
} from "@/api/operateCenter/banner/index";
import moment from "moment";
import { cloneDeep } from "lodash-es";

const loading = ref<boolean>(false);
const dragvalue = ref<boolean>(false);
const tableData = ref<Array<any>>([]);
const randN = Math.floor(Math.random() * 100000); // 生成随机数，保证每个图片不走浏览器缓存
const form = {
  keyword: "",
};
const formData = reactive(Object.assign({}, form));

const columns = reactive([
  { prop: "sort", label: "排序", slotName: "sort", minWidth: 80 },
  { prop: "id", label: "Id", minWidth: 80 },
  {
    prop: "path",
    slotName: "path	",
    label: "轮播图",
    showOverflowTooltip: false,
    minWidth: 160,
  },
  { prop: "title", label: "标题", minWidth: 140 },
  { prop: "description", label: "描述", minWidth: 140 },
  { prop: "enabled", slotName: "enabled", label: "启用状态", minWidth: 100 },
  { prop: "creatorName", label: "创建人", minWidth: 140 },
  {
    prop: "createAt",
    label: "创建时间",
    minWidth: 155,
    formatter: (row: Record<string, any>) => {
      if (!row?.createAt) return "";
      return moment(row?.createAt + "Z").format("YYYY-MM-DD");
    },
  },
  { prop: "operator", slotName: "operator", label: "操作", width: 150 },
]);

// 拖拽表格行
const dragTable = async () => {
  const tbody: any = document.querySelector(".el-table__body-wrapper tbody");
  Sortable.create(tbody, {
    handle: ".move",
    onMove() {
      dragvalue.value = true;
    },
    async onEnd({ newIndex, oldIndex }) {
      dragvalue.value = false;
      // console.log('旧序号--"' + oldIndex + '"新序号---"' + newIndex + '"');
      let tempData = cloneDeep(tableData.value);
      const currentRow = tempData.splice(oldIndex, 1)[0]; // 将oldIndex位置的数据删除并取出，oldIndex后面位置的数据会依次前移一位
      tempData.splice(newIndex, 0, currentRow); // 将被删除元素插入到新位置（currRow表示上面的被删除数据）

      let ids = await tempData.map((item: Record<string, any>) => {
        return item.id;
      });
      if (ids?.length) {
        sortBanner({ imageIds: ids }).then(() => {
          getList();
        });
      }
    },
  });
};

const getList = () => {
  loading.value = true;
  tableData.value = [];
  getBannerList(formData.keyword)
    .then((res: any) => {
      tableData.value = res;
    })
    .finally(() => {
      loading.value = false;
    });
};

// 重置
const resetList = () => {
  Object.assign(formData, form);
  getList();
};

// 新增
const infoRef = ref();
const addApps = () => {
  infoRef.value.showDialog();
};

// 编辑
const handleEdit = (val: Record<string, any>) => {
  infoRef.value.showDialog(val);
  // ElMessageBox.alert(
  //   `轮播图为全局小程序共用，是否确认修改全局小程序轮播图？`,
  //   "提醒",
  //   {
  //     confirmButtonText: "确定",
  //     type: "warning",
  //     callback: (action: Action) => {
  //       if (action == "confirm") {
  //         infoRef.value.showDialog(val);
  //       }
  //     },
  //   }
  // );
};

// 删除
const handleDelete = (val: Record<string, any>) => {
  if (val.enabled) return ElMessage.error("抱歉，不允许删除启用状态下的轮播图");
  ElMessageBox.alert(`确定要删除标题为"${val?.title}" 的轮播图吗？`, "提醒", {
    confirmButtonText: "确定",
    callback: (action: Action) => {
      if (action == "confirm") {
        deleteBanner(val?.id).then(() => {
          ElMessage.success(`删除成功`);
          getList();
        });
      }
    },
  });
};

// 启用禁用
const handleStatus = (val: Record<string, any>) => {
  ElMessageBox.alert(
    `确定要${val?.enabled ? "禁用" : "启用"}标题为 "${
      val?.title
    }" 的轮播图吗？`,
    "提醒",
    {
      confirmButtonText: "确定",
      callback: (action: Action) => {
        if (action == "confirm") {
          let params = {
            id: val?.id,
            enabled: !val?.enabled,
          };
          statusBanner(params).then(() => {
            ElMessage.success(`${val?.enabled ? "禁用" : "启用"}成功`);
            getList();
          });
        }
      },
    }
  );
};

onMounted(() => {
  getList();
  dragTable();
});
</script>

<style lang="scss" scoped>
.table_box_wrapper {
  padding-top: 10px;
  margin-top: 15px;
  background-color: #fff;

  .allocation_app {
    padding: 12px 0 5px 10px;
  }
}

.table_box {
  padding: 10px;
  border-radius: 4px;

  .movie_box {
    display: flex;
    align-items: center;

    .img {
      width: 100px;
      object-fit: contain;

      :deep(.el-image__error) {
        height: 60px;
      }

      .image-slot {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 60px;
        font-size: 30px;
        color: var(--el-text-color-secondary);
        background: var(--el-fill-color-light);

        .el-icon {
          font-size: 22px;
        }
      }
    }
  }
}
</style>
